import React, { useState, memo, useEffect, useRef } from 'react';
import { Table, Row, Col, message, Dialog } from 'tdesign-react';
import { getListApi } from 'api/useManage/userStaticIp';
import classnames from 'classnames';
import CommonStyle from 'styles/common.module.less';
import useLoading from 'hooks/useLoading';
import {
  ALL_PROVIDER_MAP,
  ALL_PROVIDER_OPTIONS,
  PACKAGE_TYPE_MAP,
  STATIC_PROVIDER_MAP,
  STATIC_PROVIDER_OPTIONS,
  USER_TYPE_MAP,
  USER_TYPE_RENEW
} from 'constants/index';
import { createColumns } from 'utils/tableUtils';
import SakuraSearchForm from 'components/SakuraSearchForm';
import SakuraModal from 'components/SakuraModal';
import { IModalRef } from 'components/SakuraModal/types';
import IppeakTable from 'components/IppeakTable';
import { EXPIRE_MAPS, ipType_OPTIONS, PARRENT_TYPE_OPTIONS, type_MAP } from './consts';
import { mapToOptions } from 'utils';

interface FormField {
  label: string;
  name: string;
  type: string;
  required?: boolean;
  options?: Array<{ label: string; value: any }>;
  disabled?: boolean;
  help?: string;
  appendSuffix?: string;
  props?: any;
}

export const SelectTable = () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<(string | number)[]>([0, 1]);
  const [visible, setVisible] = useState(false);
  const [dialogVisible, setDialogVisible] = useState(false);
  const [currentRow, setCurrentRow] = useState<any>(null);
  const { loading, setLoading } = useLoading(false);
  const [opType, setOpType] = useState<'Add' | 'Edit'>('Add');
  const [editingItem, setEditingItem] = useState<any>(null);
  const modalRef = useRef<IModalRef | any>(null);
  const initData = {
    status: 1,
    pack_type: '1',
    order_type: 9,
    email: '',
  };
  const fields: FormField[] = [
    { label: '邮箱', name: 'email', type: 'input', required: true },
    {
      label: '套餐类型',
      name: 'pack_type',
      type: 'select',
      options: [{ label: '流量', value: 1 }],
      required: true,
      disabled: true,
    },
    { label: '流量', name: 'flow', type: 'input', required: true, appendSuffix: 'G' },
    { label: '时效', name: 'day', type: 'input', required: true, appendSuffix: '天' },
    {
      label: '订单类型',
      name: 'order_type',
      type: 'select',
      options: [],
      disabled: true,
      help: '试用订单仅对没有GB套餐的用户生效；',
    },
    { label: '备注', name: 'remarks', type: 'textarea', props: { autosize: { minRows: 3, maxRows: 10 } } },
  ];
  const columns = createColumns([
    {
      label: '静态订单号',
      key: 'order_id',
      width: '280',
    },
    {
      label: '用户ID',
      key: 'user_id',
    },
    {
      label: '邮箱',
      key: 'username',
      width: '200',
    },
    {
      label: '用户类型',
      key: 'tags',
      render({ row }: any) {
        return row.tags == 'vip' ? (
          <span style={{ color: '#7868e6', cursor: 'pointer' }}>{USER_TYPE_MAP[row.tags] || '-'}</span>
        ) : row.tags == 'staff' ? (
          <span style={{ color: '#f80', cursor: 'pointer' }}>{USER_TYPE_MAP[row.tags] || '-'}</span>
        ) : (
          USER_TYPE_MAP[row.tags] || '-'
        );
      },
    },
    {
      label: 'IP地址',
      key: 'ip',
      width: '150',
    },
    {
      label: '端口号',
      key: 'port',
      width: '150',
    },
    {
      label: '国家-地区',
      key: 'region',
    },
    {
      label: '类型',
      key: 'type',
      render({ row }: any) {
        if (row.who_type == 2) {
          return row.source_tag == 'native' ? '原生' : '非原生';
        } else {
          return row.type == 15 ? '原生' : '非原生';
        }
      },
    },
    {
      label: '时效',
      key: 'aging',
      type: 'date',
      render({ row }: any) {
        return row.aging ? `${row.aging}DAY` : '-';
      },
    },
    {
      label: '剩余天数',
      key: 'day',
      width: '120',
    },
    {
      label: '续费状态',
      key: 'typedw',
      render({ row }: any) {
        const handleClick = () => {
          console.log('当前行数据:', row);
          setCurrentRow(row);
          setDialogVisible(true);
        };

        return (
          <>
            <span onClick={handleClick} style={{ cursor: 'pointer' }}>
              {row.source_tag === 'native' ? '已续费' : '未续费'}
            </span>
          </>
        );
      },
    },
    {
      label: '分配时间',
      key: 'created',
      type: 'date',
      width: '170',
    },
    {
      label: '到期时间',
      key: 'expire',
      type: 'date',
      width: '170',
    },
    {
      label: '资源商',
      key: 'parrent_type',
      enumConf: {
        options: STATIC_PROVIDER_MAP,
      },
      width: '170',
    },
    {
      label: '资源商参数',
      key: 'parent_info',
      width: '180',
    },
    // {
    //   label: '操作人',
    //   key: 'creator',
    // },
    // {
    //   label: '操作时间',
    //   key: 'opt_time',
    //   type: 'date',
    // },
  ]);
  const [table, setTable] = useState({
    list: [],
    total: 0,
    current: 1,
    pageSize: 10,
  });
  const [query, setQuery] = useState({
    page: 1,
    page_size: 10,
  });
  const formFields: any[] = [
    {
      label: '用户ID',
      name: 'uid',
      type: 'input',
      colWrap: {
        colSpan: 1.5,
        labelWidth: 60,
      },
    },
    {
      label: '邮箱',
      name: 'username',
      type: 'input',
      colWrap: {
        colSpan: 1.5,
        labelWidth: 50,
      },
    },
    {
      label: '请选择用户类型',
      name: 'tags',
      type: 'select',
      options: Object.keys(USER_TYPE_MAP).map((key) => ({
        label: USER_TYPE_MAP[key],
        value: key,
      })),
      colWrap: {
        colSpan: 1.5,
        labelWidth: 70,
      },
    },

    {
      label: '静态订单号',
      name: 'order',
      type: 'input',
      colWrap: {
        colSpan: 1.5,
        labelWidth: 90,
      },
    },
    {
      label: 'IP地址',
      name: 'ip',
      type: 'input',
      colWrap: {
        colSpan: 1.5,
        labelWidth: 55,
      },
    },
    {
      label: '到期状态',
      name: 'status',
      type: 'select',
      options: mapToOptions(EXPIRE_MAPS),
      colWrap: {
        colSpan: 1.5,
        labelWidth: 70,
      },
    },
    {
      label: '请选择续费状态',
      name: 'tags',
      type: 'select',
      options: Object.keys(USER_TYPE_RENEW).map((key) => ({
        label: USER_TYPE_RENEW[key],
        value: key,
      })),
      colWrap: {
        colSpan: 1.5,
        labelWidth: 100,
      },
    },
    {
      label: 'IP类型',
      name: 'type',
      type: 'select',
      options: ipType_OPTIONS,
      colWrap: {
        colSpan: 1.5,
        labelWidth: 60,
      },
    },
    {
      label: '资源商',
      name: 'provider',
      type: 'select',
      options: STATIC_PROVIDER_OPTIONS,
      colWrap: {
        colSpan: 1.5,
        labelWidth: 60,
      },
    },
    // {
    //   label: '用户类型',
    //   name: 'tags',
    //   type: 'select',
    //   options: Object.keys(USER_TYPE_MAP).map((key) => ({
    //     label: USER_TYPE_MAP[key],
    //     value: key,
    //   })),
    //   colWrap: {
    //     colSpan: 1.5,
    //     labelWidth: 70,
    //   },
    // },
    {
      label: '分配时间',
      name: 'created_after',
      type: 'date',
      colWrap: {
        colSpan: 1.5,
        labelWidth: 70,
      },
      props: {
        placeholder: '请选择开始时间',
        clearable: true,
      },
    },
  ];
  const { list, total, current, pageSize } = table;
  const fetchUserList = async (params?: any) => {
    setLoading(true);
    try {
      const res: any = await getListApi({ ...params, ...query });
      setLoading(false);
      setTable((pre: any) => ({
        ...pre,
        list: res.results || [],
        total: res.total || 0,
        pageSize: res.page_size || 10,
        current: res.page || 1,
      }));
    } catch (err) {
      console.log(err, 'err');
    }
  };
  useEffect(() => {
    const fetchData = async () => {
      await fetchUserList();
    };
    fetchData();
  }, []);

  function onSelectChange(value: (string | number)[]) {
    setSelectedRowKeys(value);
  }

  const handleAddClick = () => {
    setVisible(true);
  };
  const handleSubmitClick = async (type: string, values: any, cb: () => void) => {
    try {
      if (type == 'Add') {
      } else {
      }
    } catch (err: any) {
      if (err.response.data.code == 40050) {
        message.error('邮箱错误或不存在');
        modalRef.current.setFieldError('email', '邮箱错误');
      }
      return;
    }
    cb && cb();
    fetchUserList();
    setVisible(false);
  };
  // 统一的字段清除处理函数
  const handleFieldClear = (fieldName: string) => {
    setQuery((prev: any) => {
      const { [fieldName]: removed, ...rest } = prev || {};
      return { ...rest };
    });
  };
  useEffect(() => {
    fetchUserList();
  }, [query]);
  const handleSearch = (values: any) => {
    const processedValues = { ...values };
    console.log('processedValues', processedValues);

    if (processedValues.created_after) {
      if (Array.isArray(processedValues.created_after)) {
        processedValues.start_time = processedValues.created_after[0]
          ? new Date(processedValues.created_after[0]).getTime() / 1000
          : undefined;
        processedValues.end_time = processedValues.created_after[1]
          ? new Date(processedValues.created_after[1]).getTime() / 1000
          : undefined;
      }
      delete processedValues.created_after;
    }
    setQuery((pre) => ({
      ...processedValues,
      page: 1,
      page_size: query.page_size,
    }));
  };
  const handleReset = () => {
    setQuery((pre) => ({
      page: 1,
      page_size: 10,
    }));
  };

  return (
    <>
      <Row>
        <Col>
          <SakuraSearchForm
            fields={formFields}
            onAddClick={handleAddClick}
            onSearch={handleSearch}
            onReset={handleReset}
            onFieldClear={handleFieldClear}
          />
        </Col>
      </Row>
      <IppeakTable
        loading={loading}
        dataSource={list}
        columns={columns}
        rowKey='index'
        tableHeight={320}
        selectedRowKeys={selectedRowKeys}
        onSelectChange={onSelectChange}
        pagination={{
          pageSize,
          total,
          current,
          showJumper: true,
          onCurrentChange(current: number, pageInfo: any) {
            setQuery((pre) => ({
              ...pre,
              page: pageInfo.current,
            }));
          },
          onPageSizeChange(size: number) {
            setQuery((pre) => ({
              ...pre,
              page_size: size,
              page: 1, // 切换每页条数时重置到第一页
            }));
          },
        }}
      />
      <SakuraModal
        ref={modalRef}
        visible={visible}
        title={'订单'}
        onClose={() => {
          setVisible(false);
        }}
        onSubmit={handleSubmitClick}
        type={opType}
        initialValues={opType == 'Edit' ? editingItem : initData}
        fields={fields}
      ></SakuraModal>
      <Dialog
        closeBtn
        closeOnEscKeydown
        closeOnOverlayClick
        footer={false}
        header='续费详情'
        mode='modal'
        onClose={() => setDialogVisible(false)}
        placement='top'
        preventScrollThrough
        showOverlay
        theme='default'
        visible={dialogVisible}
      >
        {currentRow && (
          <Table
            data={[
              { key: 'IP地址', value: currentRow.ip },
              { key: '续费状态', value: currentRow.source_tag === 'native' ? '已续费' : '未续费' },
              { key: '订单号', value: currentRow.order_id },
              { key: '用户ID', value: currentRow.user_id },
              { key: '端口号', value: currentRow.port },
            ]}
            columns={[
              { title: '属性', colKey: 'key', width: 100 },
              { title: '值', colKey: 'value' },
            ]}
            bordered
            size='small'
          />
        )}
      </Dialog>
    </>
  );
};

const selectPage: React.FC = () => (
  <div className={classnames(CommonStyle.pageWithPadding, CommonStyle.pageWithColor)}>
    <SelectTable />
  </div>
);

export default memo(selectPage);
